package com.emm.yixun.website.listeners;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.emm.yixun.common.model.enums.*;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;

import com.emm.yixun.common.enums.ResponseEnums;
import com.emm.yixun.common.model.ActcommitLog;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.FamilyMember;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.dto.ActcommitLogDto;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.NoticeEntity;
import com.emm.yixun.common.model.dto.SignedDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.FamilyMemberServiceFacade;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;
import com.emm.yixun.system.service.notice.signed.SignedChangeNameNoticeFacade;
import com.emm.yixun.system.service.notice.subscribe.SubscribeChangeNameNoticeFacade;
import com.emm.yixun.website.common.utils.SpringWebContextUtil;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.service.system.log.ActCommitLogService;
import org.apache.commons.lang.StringUtils;

public class SignedChangeNameListeners implements Serializable, ExecutionListener {
	private static final long serialVersionUID = 1L;

	@Override
	public void notify(DelegateExecution execution) throws Exception {
		String businessAbnormaId = execution.getProcessBusinessKey();
		String processInstanceId = execution.getProcessInstanceId();
		BusinessAbnormaServiceFacade businessAbnormaServiceFacade = getBusinessAbnormaServiceFacade();
		Response<BusinessAbnorma> businessAbnormaResponse = businessAbnormaServiceFacade.findById(Long
				.valueOf(businessAbnormaId));
		CustomerServiceFacade customerServiceFacade = getCustomerServiceFacade();
		if (!businessAbnormaResponse.isSuccess()) {
			throw new Exception("更名记录不存在");
		}
		BusinessAbnorma businessAbnorma = businessAbnormaResponse.getEntity();
		if (null == businessAbnorma) {
			throw new Exception("更名记录记录不存在");
		}

		if (getActivitiProcessServiceImpl().isCheckPass(processInstanceId)) {
			
			boolean flag = checkAuditCommit(businessAbnorma);
			if(!flag) {
				throw new Exception(ResponseEnums.RESPONSEENUMS_999999.getName());
			}
			
			// 审核通过
			/**
			 * 1.修改审核状态为审核通过 2.更改签约的业务类型为已更名 3.修改签约记录的共同购房者
			 */
			BusinessAbnormaDto updateAbnorma = new BusinessAbnormaDto();
			updateAbnorma.setId(businessAbnorma.getId());
			updateAbnorma.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			updateAbnorma.setCheckDate(Calendar.getInstance().getTime()); //审核时间
			Response<Integer> upResponse = getBusinessAbnormaServiceFacade().updateByPrimaryKey(updateAbnorma, true);
			if (!upResponse.isSuccess() || upResponse.getEntity() <= 0) {
				throw new RuntimeException("更新签约更名审批状态失败");
			}

			FamilyMemberServiceFacade familyMemberServiceFacade = getFamilyMemberServiceFacade();

			if (businessAbnorma.getBusinessType().equals(BusinessAbnormaEnum.BusinessAbnorma_6.getNo())) {
				SignedServiceFacade signedServiceFacade = getSignedServiceFacade();
				Response<Signed> signedResponse = signedServiceFacade.findById(businessAbnorma.getBusinessId());
				if (!signedResponse.isSuccess()) {
					throw new Exception("签约记录不存在");
				}
				Signed signed = signedResponse.getEntity();
				if (null == signed) {
					throw new Exception("签约记录不存在");
				}
				SignedDto signedDto = new SignedDto();
				signedDto.setId(signed.getId());
				signedDto.setBusinessStatus(BusinessStatusEnum.RENAMED.getNo());
				Response<Integer> upResponseCount = getSignedServiceFacade().updateByPrimaryKey(signedDto, true);
				if (!upResponseCount.isSuccess() || upResponseCount.getEntity() <= 0) {
					throw new RuntimeException("更新签约业务状态为已更名失败");
				}
				//原始客户
				Customer originalCustomer = customerServiceFacade.findById(signed.getCustomerId()).getEntity();
				// 删除签约共同购房者
				FamilyMemberDto familyMemberDto = new FamilyMemberDto();
				familyMemberDto.setBuyId(signed.getId());
				familyMemberDto.setMemberType(MemberTypeEnum.SIGNED.getNo());
				ResponseList<FamilyMember> list = familyMemberServiceFacade.findByDto(familyMemberDto);
				if (null != list && null != list.getEntity()) {
					for (FamilyMember fm : list.getEntity()) {
						familyMemberServiceFacade.deleteByPrimaryKey(fm.getId());
					}
				}

				// 查询更名单的共同购房者
				FamilyMemberDto cnFamilyMemberDto = new FamilyMemberDto();
				cnFamilyMemberDto.setBuyId(businessAbnorma.getId());
				cnFamilyMemberDto.setMemberType(MemberTypeEnum.SIGNEDCHANGENAME.getNo());
				ResponseList<FamilyMember> changeNameList = familyMemberServiceFacade.findByDto(cnFamilyMemberDto);
				if (null != changeNameList && null != changeNameList.getEntity()) {
					for (FamilyMember fm : changeNameList.getEntity()) {
						FamilyMemberDto familyMemberRow = new FamilyMemberDto();
						familyMemberRow.setMemberName(fm.getMemberName());
						familyMemberRow.setDocumentType(fm.getDocumentType());
						familyMemberRow.setDocumentNumber(fm.getDocumentNumber());
						familyMemberRow.setCustomerId(signed.getCustomerId());
						familyMemberRow.setBuyId(signed.getId());

						familyMemberRow.setProjectId(signed.getProjectId());
						familyMemberRow.setProjectCode(signed.getProjectCode());
						familyMemberRow.setMemberType(MemberTypeEnum.SIGNED.getNo());
						familyMemberRow.setMobile(fm.getMobile());
						familyMemberRow.setAccessCode(signed.getAccessCode());
						familyMemberRow.setUserCode(signed.getUserCode());
						familyMemberRow.setMerchantId(signed.getMerchantId());
						familyMemberRow.setCreateUserId(signed.getCreateUserId());
						familyMemberRow.setDelFlag("0");
						familyMemberRow.setUpdateUserId(signed.getCreateUserId());
						familyMemberRow.setUpdateTime(new Date());
						familyMemberRow.setIsDefault("0");
						familyMemberRow.setSex("3");
						Response<FamilyMemberDto> saveResult = familyMemberServiceFacade.save(familyMemberRow);
						if (!saveResult.isSuccess())
							throw new RuntimeException("更名共同购房者替换签约共同购房者失败");
					}
				}

				// 更新新客户信息
				cnFamilyMemberDto = new FamilyMemberDto();
				cnFamilyMemberDto.setBuyId(businessAbnorma.getId());
				cnFamilyMemberDto.setMemberType(MemberTypeEnum.N_CUSTOMER_INFO.getNo());
				ResponseList<FamilyMember> responseList = familyMemberServiceFacade.findByDto(cnFamilyMemberDto);
				if (null != responseList && null != responseList.getEntity() && responseList.getEntity().size() > 0) {
					if (responseList.getEntity().size() > 1) {
						throw new RuntimeException("更新新客户信息失败，新客户信息只能是一个");
					}
					//JHSong start
					//更名的新客户
					FamilyMember familyMember = responseList.getEntity().get(0);
					//根据新客户手机号码查询客户是否存在
					String mobile = familyMember.getMobile();
					CustomerDto cusDto = new CustomerDto();
					cusDto.setCustomerPhone(mobile);
					cusDto.setMerchantId(familyMember.getMerchantId());
					cusDto.setProjectId(familyMember.getProjectId());
					cusDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					ResponseList<Customer> cusResList = customerServiceFacade.findByDto(cusDto);
					if (cusResList.isSuccess() && null != cusResList) {
						List<Customer> customerList = cusResList.getEntity();
						Customer customer = null;
						if(null != customerList && customerList.size() > 0){
							//存在客户信息
							customer = customerList.get(0);
							//修改客户信息
							CustomerDto customerDto = new CustomerDto();
							customerDto.setId(customer.getId());
							customerDto.setCustomerName(familyMember.getMemberName());
							customerDto.setPeDocumentType(familyMember.getDocumentType());
							customerDto.setPeDocumentNumber(familyMember.getDocumentNumber());
							customerDto.setCustomerPhone(familyMember.getMobile());
							/***
							 * 20190218需求: 认购&签约更名后客户数据自动赋予
							 * 1、客户等级 A 级别
							 * 2、根据身份证确定性别
							 * 3、新客户所属经纪人为原客户所属经纪人
							 *   3.1、存在客户: 客户所属经纪人不做变更
							 *   3.2、不存在客户: 客户经纪人为签约原客户的经纪人
							 */
							customerDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
							customerDto.setCustomerSex(getSexByIdCard(familyMember.getDocumentNumber()));
							customerDto.setCustomerStatus(CustomerStatusEnum.QIANYUE.getNo());
							boolean perfectFlag = customerServiceFacade.checkCustomerPerfect(customer.getId());
							customerDto.setIsIntentionIntact(IntentionIntactEnum.UN_PERFECT.getNo());
							if(perfectFlag){
								customerDto.setIsIntentionIntact(IntentionIntactEnum.PERFECT.getNo());
							}
							//此处编辑客户,不修改用户所属经纪人.
							//因无法确定修改后,客户原有历史交易等问题.
							//customerDto.setUserCode(originalCustomer.getUserCode());
							Response<Integer> response = customerServiceFacade.updateByPrimaryKey(customerDto, true);
							if (!response.isSuccess()) {
								throw new RuntimeException("更新新客户信息失败,客户id：" + familyMember.getCustomerId());
							}else{
								//认购客户与新客户非同一人,修改认购客户信息
								if(signed.getCustomerId() != customer.getId()){
									SignedDto signDto = new SignedDto();
									signDto.setId(signed.getId());
									signDto.setCustomerId(customer.getId());
									response = signedServiceFacade.updateByPrimaryKey(signDto, true);
									if (!response.isSuccess()) {
										throw new RuntimeException("更新新客户信息失败,客户id：" + familyMember.getCustomerId());
									}
									//修改原客户状态
									updateOldCustomerStatus(signed.getCustomerId());
								}
							}
							/********此处后续是否要修改认购相关的待收款等信息,有待进一步处理********/
						}else{
							//手机号为查找到客户信息,新添加一个客户,并将认购绑定到此客户上
							CustomerDto customerDto = new CustomerDto();
							customerDto.setProjectId(signed.getProjectId());
							customerDto.setProjectCode(signed.getProjectCode());
							customerDto.setCustomerName(familyMember.getMemberName());
							customerDto.setCustomerPhone(familyMember.getMobile());
							customerDto.setMerchantId(familyMember.getMerchantId());
							customerDto.setUserCode(originalCustomer.getUserCode());
							customerDto.setAccessCode(signed.getAccessCode());
							customerDto.setCreateUserId(familyMember.getCreateUserId());
							customerDto.setPeDocumentType(familyMember.getDocumentType());
							customerDto.setPeDocumentNumber(familyMember.getDocumentNumber());
							customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
							/**
							 * 20190218需求: 认购&签约更名后客户数据自动赋予
							 * 说明见上面描述
							 */
							customerDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
							customerDto.setCustomerSex(getSexByIdCard(familyMember.getDocumentNumber()));
							customerDto.setCustomerStatus(CustomerStatusEnum.QIANYUE.getNo());
							
							Response<CustomerDto> customerRes = customerServiceFacade.save(customerDto);
							if(customerRes.isSuccess()){
								//新增客户成功,绑定新客户
								customerDto = customerRes.getEntity();
								SignedDto signDto = new SignedDto();
								signDto.setId(signed.getId());
								signDto.setCustomerId(customerDto.getId());
								Response<Integer> response =  signedServiceFacade.updateByPrimaryKey(signDto, true);
								if (!response.isSuccess()) {
									throw new RuntimeException("更新新客户信息失败,客户id：" + familyMember.getCustomerId());
								}
								
								//修改原客户状态
								updateOldCustomerStatus(signed.getCustomerId());
							}
							/********此处后续是否要修改认购相关的待收款等信息,有待进一步处理********/
						}
					}else{
						//找不到客户信息,直接修改客户名字身份证等.
						CustomerDto customerDto = new CustomerDto();
						customerDto.setId(familyMember.getCustomerId());
						customerDto.setCustomerName(familyMember.getMemberName());
						customerDto.setPeDocumentType(familyMember.getDocumentType());
						customerDto.setPeDocumentNumber(familyMember.getDocumentNumber());
						customerDto.setCustomerPhone(familyMember.getMobile());

						/**
						 * 20190218需求: 认购&签约更名后客户数据自动赋予
						 * 说明见上面描述
						 */
						customerDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
						customerDto.setCustomerSex(getSexByIdCard(familyMember.getDocumentNumber()));
						//此处编辑客户,不修改用户所属经纪人.
						//因无法确定修改后,客户原有历史交易等问题.
						//customerDto.setUserCode(originalCustomer.getUserCode());

						Response<Integer> response = customerServiceFacade.updateByPrimaryKey(customerDto, true);
						if (!response.isSuccess()) {
							throw new RuntimeException("更新新客户信息失败,客户id：" + familyMember.getCustomerId());
						}
					}
					customerServiceFacade.changeCustomerLevel(signed.getCustomerId(), IntentionLevelEnum.C.getNo());
				}

				/**
				 * （签约更名流程审核通过）推送消息到app
				 * 
				 * @author ny
				 * @param param
				 *            noticeType 提醒类型, noticeBusinessId 业务主键Id
				 * @return 更名审核结果【${auditStatus}】房号：${roomName}；客户：${customer};
				 */
				NoticeEntity noticeEntity = new NoticeEntity();
				noticeEntity.setNoticeBusinessId(signed.getId());
				noticeEntity.setNoticeType("13");
				noticeEntity.setProcessInstanceId(processInstanceId);
				getSignedChangeNameNoticeFacade().createSignedChangeNameNotice(noticeEntity);
			} else if (businessAbnorma.getBusinessType().equals(BusinessAbnormaEnum.BusinessAbnorma_11.getNo())) {
				SubscribeServiceFacade subscribeServiceFacade = getSubscribeServiceFacade();
				Response<Subscribe> subscribeResponse = subscribeServiceFacade
						.findById(businessAbnorma.getBusinessId());
				if (!subscribeResponse.isSuccess()) {
					throw new Exception("签约记录不存在");
				}
				Subscribe subscribe = subscribeResponse.getEntity();
				if (null == subscribe) {
					throw new Exception("签约记录不存在");
				}

				SubscribeDto subscribeDto = new SubscribeDto();
				subscribeDto.setId(subscribe.getId());
				subscribeDto.setBusinessStatus(BusinessStatusEnum.RENAMED.getNo());
				Response<Integer> upResponseCount = subscribeServiceFacade.updateByPrimaryKey(subscribeDto, true);
				if (!upResponseCount.isSuccess() || upResponseCount.getEntity() <= 0) {
					throw new RuntimeException("更新认购业务状态为已更名失败");
				}

				//原始客户
				Customer originalCustomer = customerServiceFacade.findById(subscribe.getCustomerId()).getEntity();
				// 删除认购共同购房者
				FamilyMemberDto familyMemberDto = new FamilyMemberDto();
				familyMemberDto.setBuyId(subscribe.getId());
				familyMemberDto.setMemberType(MemberTypeEnum.SUBSCRIBE.getNo());
				ResponseList<FamilyMember> list = familyMemberServiceFacade.findByDto(familyMemberDto);
				if (null != list && null != list.getEntity()) {
					for (FamilyMember fm : list.getEntity()) {
						familyMemberServiceFacade.deleteByPrimaryKey(fm.getId());
					}
				}

				// 查询更名单的共同购房者
				FamilyMemberDto cnFamilyMemberDto = new FamilyMemberDto();
				cnFamilyMemberDto.setBuyId(businessAbnorma.getId());
				cnFamilyMemberDto.setMemberType(MemberTypeEnum.SUBSCRIBECHANGENAME.getNo());
				ResponseList<FamilyMember> changeNameList = familyMemberServiceFacade.findByDto(cnFamilyMemberDto);
				if (null != changeNameList && null != changeNameList.getEntity()) {
					for (FamilyMember fm : changeNameList.getEntity()) {
						FamilyMemberDto familyMemberRow = new FamilyMemberDto();
						familyMemberRow.setMemberName(fm.getMemberName());
						familyMemberRow.setDocumentType(fm.getDocumentType());
						familyMemberRow.setDocumentNumber(fm.getDocumentNumber());
						familyMemberRow.setCustomerId(subscribe.getCustomerId());
						familyMemberRow.setBuyId(subscribe.getId());
						familyMemberRow.setMobile(fm.getMobile());

						familyMemberRow.setProjectId(subscribe.getProjectId());
						familyMemberRow.setProjectCode(subscribe.getProjectCode());
						familyMemberRow.setMemberType(MemberTypeEnum.SUBSCRIBE.getNo());

						familyMemberRow.setAccessCode(subscribe.getAccessCode());
						familyMemberRow.setUserCode(subscribe.getUserCode());
						familyMemberRow.setMerchantId(subscribe.getMerchantId());
						familyMemberRow.setCreateUserId(subscribe.getCreateUserId());
						familyMemberRow.setDelFlag("0");
						familyMemberRow.setUpdateUserId(subscribe.getCreateUserId());
						familyMemberRow.setUpdateTime(new Date());
						familyMemberRow.setIsDefault("0");
						familyMemberRow.setSex("3");
						Response<FamilyMemberDto> saveResult = familyMemberServiceFacade.save(familyMemberRow);
						if (!saveResult.isSuccess())
							throw new RuntimeException("更名共同购房者替换签约共同购房者失败");
					}
				}

				// 更新新客户信息
				cnFamilyMemberDto = new FamilyMemberDto();
				cnFamilyMemberDto.setBuyId(businessAbnorma.getId());
				cnFamilyMemberDto.setMemberType(MemberTypeEnum.N_CUSTOMER_INFO.getNo());
				ResponseList<FamilyMember> responseList = familyMemberServiceFacade.findByDto(cnFamilyMemberDto);
				if (null != responseList && null != responseList.getEntity() && responseList.getEntity().size() > 0) {
					if (responseList.getEntity().size() > 1) {
						throw new RuntimeException("更新新客户信息失败，新客户信息只能是一个");
					}
					//更名的新客户
					FamilyMember familyMember = responseList.getEntity().get(0);
					//根据新客户手机号码查询客户是否存在
					String mobile = familyMember.getMobile();
					CustomerDto cusDto = new CustomerDto();
					cusDto.setCustomerPhone(mobile);
					cusDto.setMerchantId(familyMember.getMerchantId());
					cusDto.setProjectId(familyMember.getProjectId());
					cusDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					ResponseList<Customer> cusResList = customerServiceFacade.findByDto(cusDto);
					if (cusResList.isSuccess() && null != cusResList) {
						List<Customer> customerList = cusResList.getEntity();
						Customer customer = null;
						if(null != customerList && customerList.size() > 0){
							//存在客户信息
							customer = customerList.get(0);
							//修改客户信息
							CustomerDto customerDto = new CustomerDto();
							customerDto.setId(customer.getId());
							customerDto.setCustomerName(familyMember.getMemberName());
							customerDto.setPeDocumentType(familyMember.getDocumentType());
							customerDto.setPeDocumentNumber(familyMember.getDocumentNumber());
							customerDto.setCustomerPhone(familyMember.getMobile());
							/**
							 * 20190218需求: 认购&签约更名后客户数据自动赋予
							 * 说明见上面描述
							 */
							customerDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
							customerDto.setCustomerSex(getSexByIdCard(familyMember.getDocumentNumber()));
							customerDto.setCustomerStatus(CustomerStatusEnum.RENGOU.getNo());
							//此处编辑客户,不修改用户所属经纪人.
							//因无法确定修改后,客户原有历史交易等问题.
							//customerDto.setUserCode(originalCustomer.getUserCode());

							Response<Integer> response = customerServiceFacade.updateByPrimaryKey(customerDto, true);
							if(response.isSuccess()){
								//认购客户与新客户非同一人,修改认购客户信息
								if(subscribe.getCustomerId() != customer.getId()){
									SubscribeDto subDto = new SubscribeDto();
									subDto.setId(subscribe.getId());
									subDto.setCustomerId(customer.getId());
									response = subscribeServiceFacade.updateByPrimaryKey(subDto, true);
									if(!response.isSuccess()){
										throw new RuntimeException("更新新客户信息失败,客户id：" + familyMember.getCustomerId());
									}
									
									//修改原客户状态
									updateOldCustomerStatus(subscribe.getCustomerId());
								}
							}else{
								throw new RuntimeException("更新新客户信息失败,客户id：" + familyMember.getCustomerId());
							}
								
							/********此处后续是否要修改认购相关的待收款等信息,有待进一步处理********/
						}else{
							//手机号未查找到客户,新添加一个客户,并将认购绑定到此客户上
							CustomerDto customerDto = new CustomerDto();
							customerDto.setProjectId(subscribe.getProjectId());
							customerDto.setProjectCode(subscribe.getProjectCode());
							customerDto.setCustomerName(familyMember.getMemberName());
							customerDto.setCustomerPhone(familyMember.getMobile());
							customerDto.setMerchantId(familyMember.getMerchantId());
							customerDto.setUserCode(originalCustomer.getUserCode());
							customerDto.setAccessCode(subscribe.getAccessCode());
							customerDto.setCreateUserId(familyMember.getCreateUserId());
							customerDto.setPeDocumentType(familyMember.getDocumentType());
							customerDto.setPeDocumentNumber(familyMember.getDocumentNumber());
							customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
							/**
							 * 20190218需求: 认购&签约更名后客户数据自动赋予
							 * 说明见上面描述
							 */
							customerDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
							customerDto.setCustomerSex(getSexByIdCard(familyMember.getDocumentNumber()));
							customerDto.setCustomerStatus(CustomerStatusEnum.RENGOU.getNo());
							Response<CustomerDto> customerRes = customerServiceFacade.save(customerDto);
							if(customerRes.isSuccess()){
								//新增客户成功,绑定新客户
								customerDto = customerRes.getEntity();
								SubscribeDto subDto = new SubscribeDto();
								subDto.setId(subscribe.getId());
								subDto.setCustomerId(customerDto.getId());
								Response<Integer> response = subscribeServiceFacade.updateByPrimaryKey(subDto, true);
								if(!response.isSuccess()){
									throw new RuntimeException("更新新客户信息失败,客户id：" + familyMember.getCustomerId());
								}
								
								//修改原客户状态
								updateOldCustomerStatus(subscribe.getCustomerId());
							}
							/********此处后续是否要修改认购相关的待收款等信息,有待进一步处理********/
						}
					}else{
						//找不到客户信息,直接修改客户名字身份证等.
						CustomerDto customerDto = new CustomerDto();
						customerDto.setId(familyMember.getCustomerId());
						customerDto.setCustomerName(familyMember.getMemberName());
						customerDto.setPeDocumentType(familyMember.getDocumentType());
						customerDto.setPeDocumentNumber(familyMember.getDocumentNumber());
						customerDto.setCustomerPhone(familyMember.getMobile());
						/**
						 * 20190218需求: 认购&签约更名后客户数据自动赋予
						 * 说明见上面描述
						 */
						customerDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
						customerDto.setCustomerSex(getSexByIdCard(familyMember.getDocumentNumber()));
						//此处编辑客户,不修改用户所属经纪人.
						//因无法确定修改后,客户原有历史交易等问题.
						//customerDto.setUserCode(originalCustomer.getUserCode());

						Response<Integer> response = customerServiceFacade.updateByPrimaryKey(customerDto, true);
						if(!response.isSuccess()){
							throw new RuntimeException("更新新客户信息失败,客户id：" + familyMember.getCustomerId());
						}
					}
					customerServiceFacade.changeCustomerLevel(subscribe.getCustomerId(), IntentionLevelEnum.C.getNo());
				}
				
				/**
				 * （认购更名流程审核通过）推送消息到app
				 * 
				 * @author ny
				 * @param param
				 *            noticeType 提醒类型, noticeBusinessId 业务主键Id
				 * @return 更名审核结果【${auditStatus}】房号：${roomName}；客户：${customer};
				 */
				NoticeEntity noticeEntity = new NoticeEntity();
				noticeEntity.setNoticeBusinessId(subscribe.getId());
				noticeEntity.setNoticeType("17");
				noticeEntity.setProcessInstanceId(processInstanceId);
				getSubscribeChangeNameNoticeFacade().createSubscribeChangeNameNotice(noticeEntity);
			}

		} else {
			
			boolean flag = checkAuditCommit(businessAbnorma);
			if(!flag) {
				throw new Exception(ResponseEnums.RESPONSEENUMS_999999.getName());
			}
			
			// 无需业务处理
			BusinessAbnormaDto updateAbnorma = new BusinessAbnormaDto();
			updateAbnorma.setId(businessAbnorma.getId());
			updateAbnorma.setAuditStatus(AuditStatusEnum.REJECT.getNo());
			Response<Integer> upResponseCount = getBusinessAbnormaServiceFacade().updateByPrimaryKey(updateAbnorma,
					true);
			if (!upResponseCount.isSuccess() || upResponseCount.getEntity() <= 0) {
				throw new RuntimeException("更新签约更名审批状态失败");
			}
			if (businessAbnorma.getBusinessType().equals(BusinessAbnormaEnum.BusinessAbnorma_6.getNo())) {
				SignedServiceFacade signedServiceFacade = getSignedServiceFacade();
				Response<Signed> signedResponse = signedServiceFacade.findById(businessAbnorma.getBusinessId());
				if (!signedResponse.isSuccess()) {
					throw new Exception("签约记录不存在");
				}
				Signed signed = signedResponse.getEntity();
				if (null == signed) {
					throw new Exception("签约记录不存在");
				}
				/**
				 * （签约更名流程审核不通过）推送消息到app
				 * 
				 * @author ny
				 * @param param
				 *            noticeType 提醒类型, noticeBusinessId 业务主键Id
				 * @return 更名审核结果【${auditStatus}】房号：${roomName}；客户：${customer};
				 */
				NoticeEntity noticeEntity = new NoticeEntity();
				noticeEntity.setNoticeBusinessId(signed.getId());
				noticeEntity.setNoticeType("13");
				noticeEntity.setProcessInstanceId(processInstanceId);
				getSignedChangeNameNoticeFacade().createSignedChangeNameNotice(noticeEntity);
			} else if (businessAbnorma.getBusinessType().equals(BusinessAbnormaEnum.BusinessAbnorma_11.getNo())) {
				SubscribeServiceFacade subscribeServiceFacade = getSubscribeServiceFacade();
				Response<Subscribe> subscribeResponse = subscribeServiceFacade.findById(businessAbnorma.getBusinessId());
				if (!subscribeResponse.isSuccess()) {
					throw new Exception("认购记录不存在");
				}
				Subscribe subscribe = subscribeResponse.getEntity();
				if (null == subscribe) {
					throw new Exception("认购记录不存在");
				}
				/**
				 * （认购更名流程审核不通过）推送消息到app
				 * 
				 * @author ny
				 * @param param
				 *            noticeType 提醒类型, noticeBusinessId 业务主键Id
				 * @return 更名审核结果【${auditStatus}】房号：${roomName}；客户：${customer};
				 */
				NoticeEntity noticeEntity = new NoticeEntity();
				noticeEntity.setNoticeBusinessId(subscribe.getId());
				noticeEntity.setNoticeType("17");
				noticeEntity.setProcessInstanceId(processInstanceId);
				getSubscribeChangeNameNoticeFacade().createSubscribeChangeNameNotice(noticeEntity);
			}
		}
	}
	
	/**
	 * 前置判断,审核记录是否已经提交,防止重复提交
	 * 产生原因: 提交审核,后台处理中时,刷新页面再次提交审核,会重复
	 * true: 可继续执行
	 * false: 不可执行
	 */
	public boolean checkAuditCommit(BusinessAbnorma entity) {
		// 业务数据为null时,默认通过.为了不改变老业务,不影响流程正常行走
		if (null == entity) {
			return true;
		}
		return getActcommitLogService().checkActCommit(entity.getAuditStatus(), entity.getMerchantId(), entity.getId(),
				entity.getProcInstId(), "签约更名", "PC");
	}

	/**
	 * 根据身份证判断性别
	 * @param idCard
	 * @return
	 */
	public String getSexByIdCard(String idCard){
		//1: 男,2:女,3:未知
		String sex = "";
		if(StringUtils.isNotBlank(idCard)){
			if(idCard.length() == 18){
				if (Integer.parseInt(idCard.substring(16).substring(0, 1)) % 2 == 0) {
					sex = "2";
				} else {
					sex = "1";
				}
			}
			if(idCard.length() == 15){
				if (Integer.parseInt(idCard.substring(14, 15)) % 2 == 0) {
					sex = "2";
				} else {
					sex = "1";
				}
			}
		}
		return sex;
	}
	
	/**
	 * 20190308 修改原客户的客户状态
	 * @param customerId
	 * @author junze.liu
	 */
	private void updateOldCustomerStatus(Long customerId) {
		//获取客户状态
		String customerStatus = getCustomerStatus(customerId);
		//修改客户状态
		CustomerDto dto = new CustomerDto();
		dto.setId(customerId);
		dto.setCustomerStatus(customerStatus);
		getCustomerServiceFacade().updateByPrimaryKey(dto, true);
	}
	/**
	 * 获取客户状态
	 * @param customerId
	 * @return
	 * @author junze.liu
	 */
	private String getCustomerStatus(Long customerId) {
		//1、查询是否有签约
		SignedDto signedDto = new SignedDto();
		signedDto.setCustomerId(customerId);
		signedDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
		ResponseList<Signed> resSigned = getSignedServiceFacade().findByDto(signedDto);
		if(resSigned.isSuccess() && resSigned.getEntity() != null) {
			//状态标记
			String status = ""; 
			for(Signed signed : resSigned.getEntity()) {
				//当业务状态1为签约或更名，业务状态2为空时，算有效签约
				if(("1".equals(signed.getBusinessStatus()) || "4".equals(signed.getBusinessStatus()) 
						&& StringUtils.isBlank(signed.getBusinessSecStatus()))) {
					//有有效签约时，返回状态为签约
					return CustomerStatusEnum.QIANYUE.getNo();
				} else if("2".equals(signed.getBusinessStatus())) {
					//有退房时，先标记有退房
					status = "2";
				}
			}
			//只有退房时，返回状态为退房
			if("2".equals(status)) {
				return CustomerStatusEnum.VACATE.getNo();
			}
		}
		//2、查询是否有认购
		SubscribeDto subscribeDto = new SubscribeDto();
		subscribeDto.setCustomerId(customerId);
		subscribeDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
		ResponseList<Subscribe> resSubscribe = getSubscribeServiceFacade().findByDto(subscribeDto);
		if(resSubscribe.isSuccess() && resSubscribe.getEntity() != null) {
			for(Subscribe subscribe : resSubscribe.getEntity()) {
				//当业务状态1为认购、认购转签约、更名或延期签约，业务状态2为空时，算有效认购
				if(("1".equals(subscribe.getBusinessStatus()) || "4".equals(subscribe.getBusinessStatus()) 
						|| "6".equals(subscribe.getBusinessStatus())) 
						&& StringUtils.isBlank(subscribe.getBusinessSecStatus())) {
					return CustomerStatusEnum.RENGOU.getNo();
				}
			}
		}
		//3、查询客户信息，判断是来电或来访
		Response<Customer> res = getCustomerServiceFacade().findById(customerId);
		if(res.isSuccess() || res.getEntity() != null) {
			Customer customer = res.getEntity();
			//来访或电转访不为空时，状态为来访，否则为来电
			if(StringUtils.isNotBlank(customer.getFtContactWay1())) {
				return CustomerStatusEnum.VISIT.getNo();
			} else if(StringUtils.isNotBlank(customer.getFtContactWay())) {
				return CustomerStatusEnum.CALL.getNo();
			}
		}
		return null;
	}
	
	private ActCommitLogService getActcommitLogService(){
		return (ActCommitLogService)SpringWebContextUtil.getApplicationContext().getBean("actCommitLogService");
	}

	private SubscribeChangeNameNoticeFacade getSubscribeChangeNameNoticeFacade() {
		return (SubscribeChangeNameNoticeFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("subscribeChangeNameNoticeFacade");
	}
	
	private SignedChangeNameNoticeFacade getSignedChangeNameNoticeFacade() {
		return (SignedChangeNameNoticeFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("signedChangeNameNoticeFacade");
	}

	private BusinessAbnormaServiceFacade getBusinessAbnormaServiceFacade() {
		return (BusinessAbnormaServiceFacade) SpringWebContextUtil.getApplicationContext().getBean(
				"businessAbnormaServiceFacade");
	}

	private CustomerServiceFacade getCustomerServiceFacade() {
		return (CustomerServiceFacade) SpringWebContextUtil.getApplicationContext().getBean("customerServiceFacade");
	}

	private ActivitiProcessServiceImpl getActivitiProcessServiceImpl() {
		return (ActivitiProcessServiceImpl) SpringWebContextUtil.getApplicationContext().getBean(
				"activitiProcessServiceImpl");
	}

	private SignedServiceFacade getSignedServiceFacade() {
		return (SignedServiceFacade) SpringWebContextUtil.getApplicationContext().getBean("signedServiceFacade");
	}

	private FamilyMemberServiceFacade getFamilyMemberServiceFacade() {
		return (FamilyMemberServiceFacade) SpringWebContextUtil.getApplicationContext().getBean(
				"familyMemberServiceFacade");
	}

	private SubscribeServiceFacade getSubscribeServiceFacade() {
		return (SubscribeServiceFacade) SpringWebContextUtil.getApplicationContext().getBean("subscribeServiceFacade");
	}
	
	private PayDepositServiceFacade getPayDepositServiceFacade(){
		return (PayDepositServiceFacade)SpringWebContextUtil.getApplicationContext().getBean("payDepositServiceFacade");
	}
}
